<template>
	<view class="message-item " v-if="content">
		<text class="message-time" v-if="!message.hideTimestamp">{{ timeShow }}</text>
		<template v-if="content.type != 'notice'">
			<template v-if="!message.is_recall">
				<view class="message-normal" :class="{ 'message-normal-self': userInfo.user_id == message.id }" @longpress.stop="showMessageMenu">
					<view class="message-face" v-if="userInfo.user_id != message.id">
						<image class="message-face-image" :src="message.avatar" mode="aspectFill" @tap="visitZone"></image>
						<template v-if="content.from_vip">
							<image class="vip-sign" :src="content.from_vip.vip_file" v-if="content.from_vip.vip_file && content.from_vip.is_vip"></image>
						</template>
					</view>
					<view class="message-chunk" :class="{ 'message-chunk-self': userInfo.user_id == message.id }">
						<text class="message-name" v-if="message.username && message.type == 'group'">{{ message.username }}</text>
						<view class="message-body">
							<view class="message-status" v-if="userInfo.user_id == message.id && message.sendStatus != 99">
								<!--  -->
								<u-loading class="message-status-image" mode="flower" size="40" :show="message.sendStatus == 0"></u-loading>
								<u-icon @click="reSend" name="error-circle-fill" color="#f00" size="40" v-if="message.sendStatus == -1"></u-icon>
								<!-- <image src="@/static/images/chat/icon-chat-send-loading.gif"  v-if="message.sendStatus == 0"></image> -->
							</view>
							<view class="message-content" :class="{ 'gift-content': content.type == 'gift' }">
								<view class="message-content-noraml" :class="{ 'message-content-noraml-self': userInfo.user_id == message.id }" v-if="content.type == 'text'">
									<text class="message-content-text" :class="{ 'message-content-text-self': userInfo.user_id == message.id }" v-if="!content.xml && !content.textList">{{ content.text }}</text>
									<block v-else>
										<block v-for="(item, index) in content.textList" :key="index">
											<text class="message-content-text" :class="{ 'message-content-text-self': userInfo.user_id == message.id }" v-if="item.type == 'text'">{{ item.text }}</text>
											<image class="message-content-emoji" v-if="item.type == 'emoji'" :src="item.text" />
										</block>
									</block>
								</view>
								<image class="message-content-emotion" v-else-if="content.type == 'emotion'" :src="emotion" mode="widthFix"></image>
								<view @click="previewImage" class="message-content-media" v-else-if="content.type == 'image'" :style="{ height: mediaSize.height + 'px', width: mediaSize.width + 'px' }">
									<image v-if="content.type == 'image'" class="message-content-image" :style="{ height: mediaSize.height + 'px', width: mediaSize.width + 'px' }" :src="message.tempFile || content.text" mode="aspectFill"></image>
									<block v-if="mediaSize.long">
										<view class="media-tag"><text class="media-tag-text">长图</text></view>
									</block>
									<!-- <view class="media-mask" v-if="message.uploadStatus != 99">
							<text class="media-mask-text">{{ message.uploadProgress }} %</text>
						</view> -->
								</view>
								<view class="message-content-media" v-else-if="content.type == 'video'" :style="{ height: mediaSize.height + 'px', width: mediaSize.width + 'px' }">
									<video @fullscreenchange="changeVideoFullScreen" :autoplay="true" v-if="videoStatus" :id="'videoPlayer' + content.randstr" class="message-content-video" :src="content.text"></video>
									<image v-else @tap.stop="playVideo" :data-randstr="content.randstr" :src="content.cover" mode="aspectFill" class="message-content-video" :style="{ height: mediaSize.height + 'px', width: mediaSize.width + 'px' }"></image>
								</view>
								<view class="message-content-voice" @click="onClickVioce" v-else-if="content.type == 'voice'" :style="{ width: 500 * voiceWidthPer + 'rpx' }">
									<image class="message-content-voice-icon" v-if="viocePlayStatus" src="@/static/images/chat/icon-chat-voice.gif" mode="aspectFit"></image>
									<image class="message-content-voice-icon" v-else src="@/static/images/chat/icon-chat-voice.png" mode="aspectFit"></image>
									<text class="message-content-voice-text">{{ duration }} ''</text>
								</view>
								<view class="message-content-location" v-else-if="content.type == 'location'">
									<image class="map-background" :src="`${staticFileDomain}/static/image/chat-message-location-background.png`" mode="aspectFill" />
									<view class="map-desc">
										<view class="map-name ">
											<text class="map-name-text">{{ content.name }}</text>
										</view>
										<view class="map-address">
											<text class="map-address-text">{{ content.address }}</text>
										</view>
									</view>
									<view class="map-btn-group">
										<view class="map-btn-item right-border" style="flex: 1.3;" @click="openLocation"><text class="map-btn-item-text">查看详情</text></view>
										<!-- #ifdef APP-PLUS -->
										<view class="map-btn-item" style="flex: 1;" @click="openMap"><text class="map-btn-item-text">去这里</text></view>
										<!-- #endif -->
									</view>
								</view>
								<view class="message-content-gift" v-else-if="content.type == 'gift'">
									<text class="message-content-gift-title">送你一个 {{ content.gift.gift_name }}</text>
									<text class="message-content-gift-price">价值 {{ content.gift.money }} 元</text>
									<image class="message-content-gift-background" :src="content.gift.thumb" mode="aspectFill"></image>
									<image class="message-content-gift-image" :class="{ 'message-content-gift-image-self': userInfo.user_id == message.id }" :src="content.gift.thumb" mode="aspectFit"></image>
								</view>
								<view class="message-content-noraml" v-else><text class="message-content-text">未知消息类型，使用新版客户端查看</text></view>
								<!-- <view class="message-content-arrow" :style="{ left: userInfo.user_id != message.id ? '-12rpx' : '' }" :class="{ 'arrow-self': userInfo.user_id == message.id }"></view> -->
							</view>
						</view>
					</view>
					<view class="message-face" v-if="userInfo.user_id == message.id">
						<image class="message-face-image" :src="message.avatar" mode="aspectFill"></image>
						<template v-if="userInfo.is_vip">
							<image class="vip-sign" :src="userInfo.vip_file" v-if="userInfo.vip_file && userInfo.is_vip"></image>
						</template>
					</view>
				</view>
			</template>
			<view class="message-system-item" v-else>
				<text class="message-system-item-text">{{ (content.nickName || message.username) + ' 撤回了一条消息' }}</text>
			</view>
		</template>

		<view class="message-system-item" v-else>
			<text class="message-system-item-text">{{ content.nickName + ' ' + content.text }}</text>
		</view>
	</view>
</template>

<script>
import Moment from '@/utils/Moment.js';
import { mapState } from 'vuex';
import Tools from '@/utils/Tools.js';
import { getSingleSessionList, getGroupSessionList } from '@/store/dispatches.js';
// import Emotion from '@/utils/Emotion.js';

export default {
	props: {
		message: {
			type: Object,
			default() {
				return {};
			}
		},
		sort: {
			type: Number,
			default: -1
		},
		current: {
			type: Number,
			default: -1
		},
		autoSend: {
			type: Boolean,
			default: true
		}
	},
	data() {
		return {
			videoContext: null,
			content: null,
			mediaSize: {},
			duration: '',
			innerAudioContext: null,
			viocePlayStatus: false,
			voiceWidthPer: 0.15,
			initialization: false,
			videoStatus: false
		};
	},
	watch: {
		// current: function(newVal, oldVal) {
		// if (this.content.type == 'video') {
		// 	if (this.sort == newVal) {
		// 		console.log('play')
		// 		this.videoContext.play();
		// 	} else {
		// 		console.log('stop')
		// 		this.videoContext.stop();
		// 	}
		// }
		// }
	},
	computed: {
		timeShow: function() {
			const msgDateMoment = Moment(this.message.timestamp * 1000);
			const todayMoment = Moment();
			if (todayMoment.format('YYYY-MM-DD') == msgDateMoment.format('YYYY-MM-DD')) {
				return msgDateMoment.format('HH:mm:ss');
			} else if (todayMoment.year() == msgDateMoment.year()) {
				return msgDateMoment.format('MM月DD日 HH:mm:ss');
			} else {
				return msgDateMoment.format('YYYY年MM月DD日 HH:mm:ss');
			}
		},
		canRevoke: function() {
			const todayMoment = Moment();
			return Math.abs(this.message.timestamp - Moment().unix()) < 3 * 60;
		}
	},
	mounted() {
		let content = {};
		if (typeof this.message.content == 'string') {
			content = JSON.parse(Tools.escape2Html(this.message.content));
		} else {
			content = this.message.content;
		}
		this.content = content;
		if (this.content.type == 'text' && this.content.xml) {
			const tempList = this.content.xml.split(',');
			const textList = [];
			for (let i = 0; i < tempList.length; i++) {
				textList.push({ type: this.$u.test.url(tempList[i]) ? 'emoji' : 'text', text: tempList[i] });
			}
			this.$set(this.content, 'textList', textList);
		} else if (this.content.type == 'image' || this.content.type == 'video') {
			if (this.content.width && this.content.height) {
				let width = this.content.width;
				let height = this.content.height;
				let long = false;
				const maxWidth = this.content.type == 'video' ? uni.upx2px(300) : uni.upx2px(200);
				if (width > maxWidth) {
					height = (maxWidth / width) * height;
					width = maxWidth;
				}
				const maxHeight = width * 1.8;
				if (height > maxHeight) {
					height = maxHeight;
					long = true;
				}
				this.mediaSize = { height, width, long };
			} else {
				this.mediaSize = { width: uni.upx2px(400), height: uni.upx2px(300), long: false };
			}
		} else if (this.content.type == 'voice') {
			this.duration = parseInt(this.content.duration);
			let voiceWidthPer = this.duration / 30;
			if (voiceWidthPer < 0.3) {
				voiceWidthPer = 0.3;
			} else if (voiceWidthPer > 1) {
				voiceWidthPer = 1;
			}
			this.voiceWidthPer = voiceWidthPer;
			this.innerAudioContext = uni.createInnerAudioContext();
			this.innerAudioContext.autoplay = false;
			this.innerAudioContext.src = content.text;
			this.innerAudioContext.onPlay(() => {
				uni.$emit('chatVoicePlay', { src: this.content.text });
				this.viocePlayStatus = true;
			});
			this.innerAudioContext.onEnded(() => {
				this.viocePlayStatus = false;
			});
			this.innerAudioContext.onStop(() => {
				this.viocePlayStatus = false;
			});
			this.innerAudioContext.onError(() => {
				this.viocePlayStatus = false;
			});
		}
		// this.content = content;

		uni.$on('chatVoicePlay', this.checkVoice);
		uni.$on('recallMessage', this.onRevoke);
	},
	beforeDestroy() {
		uni.$off('chatVoicePlay', this.checkVoice);
		uni.$off('recallMessage', this.onRevoke);
	},
	methods: {
		checkVoice(data) {
			if (this.innerAudioContext) {
				if (this.content.text != data.src) {
					this.innerAudioContext.stop();
				}
			}
		},
		playVideo(e) {
			const randstr = e.currentTarget.dataset.randstr;
			if (randstr) {
				this.videoStatus = true;
				this.$nextTick(() => {
					const createVideoContext = uni.createVideoContext(`videoPlayer${e.currentTarget.dataset.randstr}`, this);
					createVideoContext.requestFullScreen({ direction: 'vertical' });
					createVideoContext.showStatusBar();
				});
			}
		},
		changeVideoFullScreen(e) {
			console.log(e);
			this.videoStatus = e.detail.fullScreen;
		},
		stopyVideo() {
			if (this.videoContext) {
				this.videoContext.stop();
			}
		},
		openLocation() {
			uni.openLocation({
				...this.content
			});
		},
		onClickVioce() {
			if (!this.viocePlayStatus) {
				this.innerAudioContext.play();
			} else {
				this.innerAudioContext.stop();
			}
		},
		openMap() {
			let url = '';
			if (plus.os.name == 'Android') {
				const hasBaiduMap = plus.runtime.isApplicationExist({ pname: 'com.baidu.BaiduMap', action: 'baidumap://' });
				const hasAmap = plus.runtime.isApplicationExist({ pname: 'com.autonavi.minimap', action: 'androidamap://' });
				const urlBaiduMap = `baidumap://map/marker?location=${this.content.latitude},${this.content.longitude}&title=${encodeURI(this.content.name)}&content=${encodeURI(this.content.address)}&src=jirizi.dianmianti.com`;
				const urlAmap = `androidamap://viewMap?sourceApplication=jirizi.dianmianti.com&poiname=${encodeURI(this.content.name)}&lat=${this.content.latitude}&lon=${this.content.longitude}&dev=0`;
				if (hasAmap && hasBaiduMap) {
					plus.nativeUI.actionSheet({ title: '选择地图应用', cancel: '取消', buttons: [{ title: '百度地图' }, { title: '高德地图' }] }, e => {
						switch (e.index) {
							case 1:
								plus.runtime.openURL(urlBaiduMap);
								break;
							case 2:
								plus.runtime.openURL(urlAmap);
								break;
						}
					});
				} else if (hasAmap) {
					plus.runtime.openURL(urlAmap);
				} else if (hasBaiduMap) {
					plus.runtime.openURL(urlBaiduMap);
				} else {
					uni.showToast({
						icon: 'none',
						title: '未安装地图应用'
					});
				}
			} else {
				plus.nativeUI.actionSheet({ title: '选择地图应用', cancel: '取消', buttons: [{ title: 'Apple地图' }, { title: '百度地图' }, { title: '高德地图' }] }, e => {
					switch (e.index) {
						case 1:
							url = `http://maps.apple.com/?address=${encodeURI(this.content.name)}&ll=${this.content.latitude},${this.content.longitude}`;
							break;
						case 2:
							url = `baidumap://map/marker?location=${this.content.latitude},${this.content.longitude}&title=${encodeURI(this.content.name)}&src=jirizi.dianmianti.com`;
							break;
						case 3:
							url = `iosamap://viewMap?sourceApplication=jirizi.dianmianti.com&poiname=${encodeURI(this.content.name)}&lat=${this.content.latitude}&lon=${this.content.longitude}&dev=0`;
							break;
						default:
							break;
					}
					if (url != '') {
						plus.runtime.openURL(url, e => {
							plus.nativeUI.alert('本机未安装指定的地图应用');
						});
					}
				});
			}
		},
		previewImage() {
			uni.previewImage({
				urls: [this.content.text],
				indicator: 'number'
			});
		},
		visitZone() {
			if (this.message.id != this.userInfo.user_id) {
				this.visitUserZone(this.message.id);
			}
		},

		reSend() {
			// #ifndef MP
			this.message.reSend();
			// #endif
		},
		onRevoke(e) {
			setTimeout(() => {
				const content = JSON.parse(e.data.content);
				if (content.nonce_str == this.content.randstr) {
					this.$set(this.message, 'is_recall', 1);
					this.innerAudioContext && this.innerAudioContext.stop();
				}
			}, 0);
		},
		showMessageMenu(e) {
			if (this.userInfo.user_id == this.message.id && this.canRevoke && this.message.sendStatus == 99) {
				const { touches } = e;
				const query = uni.createSelectorQuery().in(this);
				query
					.select('.message-chunk')
					.boundingClientRect(data => {
						const minTop = data.top;
						const maxTop = data.top + data.height;
						let y = 0;
						if (minTop > uni.getSystemInfoSync().windowHeight / 2) {
							y = minTop;
						} else {
							y = maxTop;
						}
						this.$emit('press', { y, x: touches[0].pageX, nonce_str: this.content.randstr });
					})
					.exec();
			}
		}
	}
};
</script>

<style lang="scss">
.message-item {
	/* #ifndef APP-NVUE */
	display: flex;
	flex-direction: column;
	/* #endif */
	padding: 20rpx 30rpx;
	position: relative;
	z-index: 20;
	align-items: center;
	overflow: visible;
}
.message-time {
	font-size: 22rpx;
	color: #a6a6a6;
	margin: 20rpx 0;
	z-index: 1;
}
.message-normal {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	position: relative;
	flex-direction: row;
	width: 100%;
}

.message-normal-self {
	justify-content: flex-end;
}

.message-face {
	width: 80rpx;
	height: 80rpx;
	position: relative;
}
.message-face-image {
	width: 80rpx;
	height: 80rpx;
	border-radius: 6rpx;
}
.vip-sign {
	width: 35rpx;
	height: 35rpx;
	position: absolute;
	right: -10rpx;
	bottom: -4rpx;
}

.message-chunk {
	/* #ifndef APP-NVUE */
	display: flex;
	flex-direction: column;
	/* #endif */
	padding: 0 20rpx;
}
.message-chunk-self {
	align-items: flex-end;
}
.message-name {
	font-size: 22rpx;
	color: #737373;
	margin-bottom: 10rpx;
}
.message-body {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
}

.message-content {
	/* #ifndef APP-NVUE */
	display: flex;
	width: max-content;
	position: relative;
	/* #endif */
	background-color: #fff;
	border-radius: 10rpx;
	overflow: hidden;
}
.gift-content {
	background-color: rgba(255, 255, 255, 0);
	border-radius: 20rpx;
	overflow: visible;
}
.message-content-noraml {
	max-width: 520rpx;
	padding: 20rpx;
	flex-direction: row;
	flex-wrap: wrap;
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
}

.message-content-text {
	color: #333333;
	font-size: 30rpx;
	line-height: 40rpx;
	/* #ifdef APP-NVUE */
	word-wrap: anywhere;
	/* #endif */
	/* #ifndef APP-NVUE */
	word-break: break-all;
	/* #endif */
}

.message-content-noraml-self {
	background-image: linear-gradient(180deg, #ed4f5d 0%, #fb7a8e 100%);
}
.message-content-text-self {
	color: #fff;
}
.message-content-emoji {
	display: inline-block;
	width: 40rpx;
	height: 40rpx;
}
.message-content-voice {
	height: 80rpx;
	background-color: #fff;
	width: 240rpx;
	flex-direction: row;
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	align-items: center;
	padding: 0 20rpx;
}
.message-content-voice-icon {
	width: 35rpx;
	height: 35rpx;
	margin-right: 15rpx;
}
.message-content-voice-text {
	font-size: 30rpx;
	line-height: 60rpx;
	color: #111;
}
.message-content-arrow {
	top: 8rpx;
	transform: rotate(45deg);
	position: absolute;
	z-index: 100;
	overflow: hidden;
	width: 24rpx;
	background-color: #fff;
	height: 24rpx;
}

.time-self {
	right: 130rpx;
	text-align: right;
}
.arrow-self {
	right: -12rpx;
}
.message-content-image {
	width: 400rpx;
}
.message-content-emotion {
	width: 120rpx;
	height: 120rpx;
}
.message-content-media {
	background-color: #fff;
}
.media-tag {
	position: absolute;
	bottom: 10rpx;
	right: 10rpx;
	z-index: 28;
	padding: 0 3px;
	border-radius: 1px;
	border-width: 0.5px;
	border-style: solid;
	border-color: #686868;
}
.media-tag-text {
	font-size: 10px;
	height: 16px;
	line-height: 16px;
	color: #686868;
}
.media-mask {
	background-color: rgba(0, 0, 0, 0.4);
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 30;
	align-items: center;
	justify-content: center;
}
.media-mask-text {
	color: #fff;
	font-size: 30rpx;
}
.message-content-video-player {
	height: 0;
	width: 0;
	position: absolute;
	left: -1000%;
	top: -1000%;
}
.message-content-video {
	width: 200rpx;
	height: 200rpx;
	z-index: 99;
}
.message-content-location {
}
.map-background {
	width: 500rpx;
	height: 300rpx;
}
.map-desc {
	padding: 15rpx 20rpx;
	width: 500rpx;
}

.map-name-text {
	font-size: 34rpx;
	line-height: 50rpx;
}
.map-address {
	margin-top: 10rpx;
}
.map-address-text {
	font-size: 24rpx;
	color: #838383;
}
.map-btn-group {
	height: 80rpx;
	flex-direction: row;
	border-top-color: #f4f4f4;
	border-top-width: 2rpx;
	border-top-style: solid;
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
}
.map-btn-item {
	justify-content: center;
	align-items: center;
	flex: 1;
	/* #ifdef H5 || APP-VUE */
	display: flex;
	/* #endif */
}
.right-border {
	border-right-width: 2rpx;
	border-right-style: solid;
	border-right-color: #f4f4f4;
}
.map-btn-item-text {
	font-size: 30rpx;
	color: $theme-main-color;
}
.message-status {
	width: 40rpx;
	height: 40rpx;
	margin-top: 20rpx;
	margin-right: 20rpx;
}
.message-status-image {
	width: 40rpx;
	height: 40rpx;
}
.message-system-item {
	width: 690rpx;
	padding: 0 50rpx;
	align-items: center;
	justify-content: center;
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
}
.message-system-item-text {
	font-size: 24rpx;
	color: #999;
}
.message-content-gift {
	width: 482rpx;
	height: 208rpx;
	border-radius: 20rpx;
	background-color: #d3c3ea;
	padding: 40rpx 75rpx;
	position: relative;
	color: #fff;
	/* #ifndef APP-NVUE */
	display: flex;
	flex-direction: column;
	/* #endif */
	justify-content: space-between;
}
.message-content-gift-title {
	color: #fff;
	font-size: 38rpx;
	z-index: 99;
}
.message-content-gift-price {
	color: #fff;
	font-size: 24rpx;
	z-index: 99;
}
.message-content-gift-background {
	position: absolute;
	z-index: 1;
	width: 482rpx;
	height: 208rpx;
	top: 0;
	left: 0;
	opacity: 0.05;
}
.message-content-gift-image {
	height: 130rpx;
	width: 130rpx;
	position: absolute;
	top: 50%;
	right: -130rpx;
	transform: translate(-50%, -50%);
	z-index: 99;
}
.message-content-gift-image-self {
	left: -130rpx;
	right: auto;
	transform: translate(50%, -50%);
}
</style>
